using System;
using System.Windows.Forms;
using MediaPortal.GUI.Library;
using MediaPortal.GUI.Video;
//using MediaPortal.Video.Database;
using MediaPortal.Util;
using MediaPortal.Dialogs;
using MediaPortal.Player;
using System.Data;
using System.ComponentModel;
using c3o.Framework.Web;
using System.Collections.Specialized;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using AzureusWrapper;

namespace MediaPortal.GUI.Rss
{
	public class GUIAzureus :  GUIDataTable, ISetupForm
	{

        [SkinControlAttribute(300)]   protected GUIButtonControl bttnRefresh = null;


        private string url;

        private AzureusHost azureusHost;
        Download[] downloads;

        private System.Windows.Forms.Timer RefreshTimer = new System.Windows.Forms.Timer();

        public override int GetID
        {
            get
            {
                return 61904;
            }
            set
            {
            }
        }

 
        protected override void OnShowContextMenu()
        {
            GUIDialogMenu dlg = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);

            if (dlg == null)
                return;

            dlg.Reset();
            dlg.SetHeading(924);                // Menu
            //			dlg.AddLocalizedString(335);		// Start
            //			dlg.AddLocalizedString(1032);		// Stop
            dlg.Add("Start");
            dlg.Add("Stop");
            dlg.Add("Move Up");
            dlg.Add("Move Down");
            dlg.Add("Remove");

            dlg.DoModal(GetID);

            switch (dlg.SelectedLabel)
            {
                case 0:       // Start
                    {
                        this.AzureusAction("Start");
                        break;
                    }

                case 1:      // Stop
                    {                        
                        this.AzureusAction("Stop");
                        break;
                    }

                case 2:      // Move Up
                    {
                        this.AzureusAction("Up");
                        break;
                    }
                case 3:      // Move Down
                    {
                        this.AzureusAction("Down");
                        break;
                    }
                case 4:      // Remove
                    {
                        this.AzureusAction("Remove");
                        break;
                    }
            }
        }


		protected override void OnPageLoad()
		{
            GUIPropertyManager.SetProperty("#header.label", "My Azureus");

			base.OnPageLoad();

            if (this.azureusHost != null)
            {
                this.ShowDownloads();
            }
            else
            {
                GUIDialogOK pDlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK);
                pDlgOK.SetHeading("Azureus " + GUILocalizeStrings.Get(257));//Error
                pDlgOK.SetLine(1, url);
                pDlgOK.DoModal(GUIWindowManager.ActiveWindow);
            }
		}



        protected override void LoadSettings()
        {
            this.xmlSection = "torrents";

            base.LoadSettings();

            MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.Settings("MediaPortal.xml");

            if (azureusHost == null)
            {
                url = xmlreader.GetValue(this.xmlSection, "Azureus.url");

                if (url == null || url.Length == 0) url = "http://127.0.0.1:6884/process.cgi";

                try
                {
                    azureusHost = new AzureusHost(url);

                    string interval = xmlreader.GetValue(this.xmlSection, "Azureus.seconds");

                    int seconds = 10;

                    if (interval != null && interval.Length > 0)
                    {
                        seconds = int.Parse(interval);
                    }

                    RefreshTimer.Interval = seconds * 1000;
                    RefreshTimer.Tick += new EventHandler(this.ShowDownloads);
                    RefreshTimer.Start();
                }
                catch
                {
                    azureusHost = null;
                }
            }
        }
			


        


        private void ShowDownloads(object sender, System.EventArgs e)
        {
            this.ShowDownloads();
        }

        //private void ShowDownloads()
        //{
        //    this.detailbox.Label = "";

        //    _AzureusTimer.Start();

        //    // Get Status from AZ
        //    this.downloads = azureusHost.GetDownloads();

        //    if (this.ListMode != "Torrents.Azureus" || this.downloads.Length != this.facadeView.Count)
        //    {
        //        this.ListMode = "Torrents.Azureus";

        //        this.selectedOutline = null;

        //        GUIControl.ClearControl(this.GetID, facadeView.GetID);
        //        this.facadeView.View = this.DefaultView;
        //    }

        //    GUIListItem item;

        //    int i = 0;

        //    foreach (Download dl in downloads)
        //    {
        //        if (i < facadeView.Count)
        //        {
        //            item = facadeView[i];
        //        }
        //        else
        //        {
        //            item = new GUIListItem();
        //        }

        //        item.Label = dl.TorrentInformation.Name;
        //        string DownLoadPercent = String.Format("{0:P2}", Double.Parse(dl.DownloadStats.Completed.ToString()) / 1000);
        //        string UploadPercent = String.Format("{0:P2}", ((double)dl.DownloadStats.Uploaded / dl.TorrentInformation.Size));
        //        item.Label2 = dl.DownloadStats.Status + " ( " + DownLoadPercent + " / " + UploadPercent + ") ";
        //        item.IsFolder = false;
        //        item.IconImage = "defaultVideo.png";
        //        item.Path = dl.TorrentInformation.GetHashCode().ToString();
//                    item.TVTag = dl;

        //        if (i >= facadeView.Count)
        //        {
        //            facadeView.Add(item);
        //        }

        //        i++;

        //        this.ShowStats();
        //    }
        //}


        protected override void OnPageDestroy(int newWindowId)
        {
            this.RefreshTimer.Stop();
        }



        public void ShowDownloads()
        {            
            // Get Status from AZ
            this.downloads = azureusHost.GetDownloads();
            
            DataTable dt = new DataTable();

            dt.Columns.Add("Label");
            dt.Columns.Add("Path");
            dt.Columns.Add("Label2");
            dt.Columns.Add("DVDLabel");
            dt.Columns.Add("IconImage");


            //String.Format("{0:P2}", ((double)dl.DownloadStats.Uploaded / dl.TorrentInformation.Size));
            //item.Label2 = dl.DownloadStats.Status + " ( " + DownLoadPercent + " / " + UploadPercent + ") ";

            foreach (Download dl in this.downloads)
            {
                //item.Label = dl.TorrentInformation.Name;
                //string DownLoadPercent = String.Format("{0:P2}", Double.Parse(dl.DownloadStats.Completed.ToString()) / 1000);
                //string UploadPercent = String.Format("{0:P2}", ((double)dl.DownloadStats.Uploaded / dl.TorrentInformation.Size));
                //item.Label2 = dl.DownloadStats.Status + " ( " + DownLoadPercent + " / " + UploadPercent + ") ";
              
                //string lKey = dl.TorrentInformation.GetHashCode().ToString();

                string lKey = dl.TorrentInformation.ObjectId;
                string status = dl.DownloadStats.Status;
                string lFileName = dl.TorrentInformation.Name;                
                string lRatio = String.Format("{0:N3}", (double) dl.DownloadStats.ShareRatio / 1000);	// 24 = 0.024             
                string lSize = GUIHelper.FormatSize((ulong) dl.TorrentInformation.Size, 1);

                //if (lUpSpeed.Length > 0) lUpSpeed = GUIHelper.FormatSize(ulong.Parse(lUpSpeed), 1);
                //if (lDownSpeed.Length > 0) lDownSpeed = GUIHelper.FormatSize(ulong.Parse(lDownSpeed), 1);

                string DownLoadPercent = String.Format("{0:P2}", Double.Parse(dl.DownloadStats.Completed.ToString()) / 1000);
                string UploadPercent = String.Format("{0:P2}", ((double)dl.DownloadStats.Uploaded / dl.TorrentInformation.Size));

                string IconImage = "Inactive.PNG";

                switch (status)
                {
                    case "Stopped":
                        IconImage = "Inactive.PNG";
                        break;
                    case "Seeding":
                        IconImage = "Seeding.PNG";
                        break;
                    case "Downloading":
                         IconImage = "Downloading.PNG";
                        break;
                }

                string DVDLabel = lFileName + "\n" + status + "\nSize: " + lSize + "\nRatio: " + lRatio ;

                dt.Rows.Add(lFileName, lKey, status + " (" + DownLoadPercent + ")", DVDLabel, IconImage);
            }

            this.Datasource = dt;
            this.Databind();

            this.Refresh();
        }





		public override bool Init()
		{
			//this.RssFileName = "MyPodCasts.Feeds.opml.xml";
			//this.OpmlFileName = "MyPodCasts.Search.opml.xml";

			//g_Player.PlayBackStopped += new MediaPortal.Player.g_Player.StoppedHandler(OnPlayBackStopped);
			//g_Player.PlayBackEnded += new MediaPortal.Player.g_Player.EndedHandler(OnPlayBackEnded);
			//g_Player.PlayBackStarted += new MediaPortal.Player.g_Player.StartedHandler(OnPlayBackStarted);
	
			//return Load(GUIGraphicsContext.Skin + @"\MyPodCasts.xml");
            return Load(GUIGraphicsContext.Skin + @"\MyAzureus.xml");
		}





		#region ISetupForm Members

		// Returns the name of the plugin which is shown in the plugin menu
		public string PluginName()
		{
			return "My Azureus";
		}



		// Returns the description of the plugin is shown in the plugin menu
		public string Description()
		{
            return "My Azureus";
		}



		// Returns the author of the plugin which is shown in the plugin menu
		public string Author()
		{
			return "fcsobel";
		}



		// show the setup dialog
		public void ShowPlugin()
		{
            Form setup = new AzureusSetupForm();            
			setup.ShowDialog();
		}



		// Indicates whether plugin can be enabled/disabled
		public bool CanEnable()
		{
			return true;
		}

		// get ID of windowplugin belonging to this setup
		public int GetWindowId()
		{
			return this.GetID;
		}

		// Indicates if plugin is enabled by default;
		public bool DefaultEnabled()
		{
			return true;
		}

		// indicates if a plugin has its own setup screen
		public bool HasSetup()
		{
			return true;
		}


		/// <summary>
		/// If the plugin should have its own button on the main menu of Media Portal then it
		/// should return true to this method, otherwise if it should not be on home
		/// it should return false
		/// </summary>
		/// <param name="strButtonText">text the button should have</param>
		/// <param name="strButtonImage">image for the button, or empty for default</param>
		/// <param name="strButtonImageFocus">image for the button, or empty for default</param>
		/// <param name="strPictureImage">subpicture for the button or empty for none</param>
		/// <returns>true  : plugin needs its own button on home
		///          false : plugin does not need its own button on home</returns>
		//public bool GetHome(out string strButtonText, out string strButtonImage, out string strButtonImageFocus, out string strPictureImage)
		//{

		//    strButtonText = "UKNova";
		//    strButtonImage = String.Empty;
		//    strButtonImageFocus = String.Empty;
		//    strPictureImage = String.Empty;
		//    return false;
		//}

		public bool GetHome(out string strButtonText, out string strButtonImage, out string strButtonImageFocus, out string strPictureImage)
		{
			strButtonText = PluginName();
			strButtonImage = String.Empty;
			strButtonImageFocus = String.Empty;
			strPictureImage = String.Empty;
			return true;
		}
		#endregion

        
        protected override void OnClicked(int controlId, GUIControl control, Action.ActionType actionType)
        {
            base.OnClicked(controlId, control, actionType);

            if (control == this.bttnRefresh) this.ShowDownloads();
        }


    	public override void OnAction(Action action)
		{
			base.OnAction(action);


            if (action.IsUserAction())
            {
                this.Refresh();
            }
		}


        protected void Refresh()
        {
            GUIListItem item = this.facadeView.SelectedListItem;
            if (item != null)
            {
                this.detailbox.Label = item.DVDLabel;
            }
        }

        protected override void OnStop()
        {
            this.AzureusAction("Stop");
        }

        protected override void OnPlay()
        {
            this.AzureusAction("Start");
        }


        private void AzureusAction(string Action)
        {
            GUIListItem item = this.facadeView.SelectedListItem;

            if (item != null)
            {
                //Download dl = item.TVTag as Download;
                
                string dl = item.Path as string;

                if (dl != null)
                {
                    switch (Action)
                    {
                        case "Remove":

                            GUIDialogYesNo dlgYesNo = (GUIDialogYesNo)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_YES_NO);
                            if (null == dlgYesNo) return;
                            dlgYesNo.SetHeading(GUILocalizeStrings.Get(433));//delete watched recordings?
                            dlgYesNo.SetLine(1, item.Label);
                            //							dlgYesNo.SetLine(2, String.Empty);
                            //							dlgYesNo.SetLine(3, String.Empty);
                            dlgYesNo.SetDefaultToYes(true);
                            dlgYesNo.DoModal(GetID);

                            if (dlgYesNo.IsConfirmed)
                            {
                                azureusHost.RemoveDownload(dl);
                            }

                            break;
                        case "Toggle":
                            if (item.IconImage == "Inactive.PNG")
                            {
                                azureusHost.StartDownload(dl);
                            }
                            else
                            {
                                azureusHost.StopDownload(dl);
                            }
                            break;
                        case "Start":
                            azureusHost.StartDownload(dl);
                            break;
                        case "Stop":
                            if (item.IconImage == "Inactive.PNG")                            
                            {
                                this.AzureusAction("Remove");
                            }
                            else
                            {
                                azureusHost.StopDownload(dl);
                            }
                            break;
                        case "Up":
                            azureusHost.MoveDownloadUp(dl);
                            break;
                        case "Down":
                            azureusHost.MoveDownloadDown(dl);
                            break;
                    }

                    this.ShowDownloads();
                }
            }
        }
           

	}
}